﻿using System;
using System.Collections.Generic;
using System.Collections.Concurrent;

namespace Ue.Infrastructure.Caching.VolatileProvider
{
    /// <summary>
    /// 对象触发缓存机制
    /// 当调用对象的Trigger后，缓存失效
    /// 此对象最好用单例
    /// </summary>
    public interface ISignals
    {
        void Trigger<T>(T signal);
        IVolatileToken When<T>(T signal);
    }

    public class Signals : ISignals
    {
        readonly IDictionary<object, Token> tokens = new ConcurrentDictionary<object, Token>();

        public void Trigger<T>(T signal)
        {
            Token token;
            if (this.tokens.TryGetValue(signal, out token))
            {
                this.tokens.Remove(signal);
                token.Trigger();
            }
        }

        public IVolatileToken When<T>(T signal)
        {
            Token token;
            if (!this.tokens.TryGetValue(signal, out token))
            {
                token = new Token();
                this.tokens[signal] = token;
            }
            return token;
        }

        class Token : IVolatileToken
        {
            public Token()
            {
                IsCurrent = true;
            }

            public bool IsCurrent { get; private set; }
            public void Trigger() { IsCurrent = false; }
        }
    }
}
